<?php
// +----------------------------------------------------------------------
// | Tplay [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://tplay.pengyichen.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 听雨 < 389625819@qq.com >
// +----------------------------------------------------------------------


namespace app\admin\controller;

use \think\Db;
use \think\Cookie;
use \think\Session;
use app\admin\model\Agent as agentModel;//管理员模型
use app\admin\model\AdminMenu;
use app\admin\controller\Permissions;
class Agent extends Permissions
{
    /**
     * 管理员列表
     * @return [type] [description]
     */
    public function index()

    {
     
        $post = $this->request->param();
        if (isset($post['keywords']) and !empty($post['keywords'])) {
            $where['phone'] = ['like', '%' . $post['keywords'] . '%'];
        }
        if(isset($post['create_time']) and !empty($post['create_time'])) {
            $min_time = strtotime($post['create_time']);
            $max_time = $min_time + 24 * 60 * 60;
            $where['add_time'] = [['>=',$min_time],['<=',$max_time]];
        }
        $res = Session::get("admin_cate_id");//获取登陆时的admin_cate_id,控制器comment中的admin_cate_id(127行）
        $ress = Session::get("admin");//获取登陆时的admin，控制器comment中的admin(126行）

        //判断登陆角色
        if ($res ==1){
            $agent = empty($where) ? Db::name('agent')->alias('a')->join('ratio b','a.id=b.agent_id')
                      ->field('a.id,name,phone,grade,charge_ratio,last_money,status,add_time,update_time,request')->order('add_time desc')->where('pid','<>',0)
                      ->paginate(20) : Db::name('agent')->alias('a')->join('ratio b','a.id=b.agent_id')
                      ->field('a.id,name,phone,grade,charge_ratio,last_money,status,add_time,update_time,request')->where($where)->where('pid','<>',0)->order('add_time desc')
                      ->paginate(20,false,['query'=>$this->request->param()]);
        }else{

            $list  = Db::name('admin')->where('id',$ress)->value('name');
            $data  = Db::name('agent')->where('phone',$list)->value('id');
            $agent = empty($where) ? Db::name('agent')->alias('a')->join('ratio b','a.id=b.agent_id')
                   ->field('a.id,name,phone,grade,charge_ratio,last_money,status,add_time,update_time,request')->order('add_time desc')->where('pid',$data)
                   ->paginate(20) : Db::name('agent')->alias('a')->join('ratio b','a.id=b.agent_id')
                   ->field('a.id,name,phone,grade,charge_ratio,status,last_money,add_time,update_time,request')->where('pid',$data)->where($where)->order('add_time desc')
                   ->paginate(20,false,['query'=>$this->request->param()]);
        }

        $this->assign('agent',$agent);
        return $this->fetch();
    }
    /*
     * 管理员个人资料修改，属于无权限操作，仅能修改昵称和头像，后续可增加其他字段
     * @return [type] [description]
     */
    public function personal()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $model = new agentModel();
        $info['agent'] = $model->alias('a')->join('ratio b','a.id=b.agent_id')->field('a.id,phone,grade,charge_ratio,status,grade,charge_ratio,weixin_num')
                         ->where('a.id',$id)->find();
                         
        $this->assign('info',$info);
        return $this->fetch();
    }

    public function update(){
        $id = input('id');
        if(!$id){
         return $this->error('缺少参数'); 
        }
          $info = Db::name('agent')->alias('a')->join('ratio b','a.id=b.agent_id')
                  ->field('a.id,a.name,phone,grade,charge_ratio,last_money,status,grade,charge_ratio,weixin_num')->where('a.id',$id)->find();

                $this->assign('info',$info);
              
                return $this->fetch();

    }


    /**
     * 管理员的添加及修改
     * @return [type] [description]
     */
    public function publish()
    {
        //获取管理员id
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;

        $model = new agentModel();
        if($id > 0) {
            //是修改操作
            if($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
              
              
                if(!preg_match("/^1[34578]{1}\d{9}$/",$post['phone'])){
                    return $this->error('提交失败：该手机号不正确');
                }
                //验证用户名是否存在
                $name = $model->where(['phone'=>$post['phone'],'id'=>['neq',$post['id']]])->select();
                if(!empty($name)) {
                    return $this->error('提交失败：该手机号已被注册');
                }


                $list = $model->allowField(true)->save($post,['id'=>$id]);
                $data['agent_id']=$id;
                $data['charge_ratio']=$post['charge_ratio'];
                $data['grade']=$post['grade'];
                
                $cate_id = Db::name('ratio')->where(['agent_id'=>$id])->value('grade');
                $rb = Db::name('ratio')->where(['agent_id'=>$id])->update($data);



                if($list || $rb) {
                     if($cate_id==0){
                         return $this->success('修改成功','admin/agents/index');
                     }else{
                         return $this->success('修改成功','admin/agent/index');
                     }
                   
                } else {
                    return $this->error('修改失败');
                }
            }else{

                $info['agent'] = Db::name('agent')->alias('a')->join('ratio b','a.id=b.agent_id')->field('a.id,a.name,phone,grade,charge_ratio,last_money,status,grade,charge_ratio,weixin_num')->where('a.id',$id)->find();
           
                $this->assign('info',$info);
              
                return $this->fetch();
            }


        } else {
            //是新增操作
            if($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['phone', 'require|alphaDash', '不能为空'],
                    ['password', 'require|confirm', '密码不能为空|两次密码不一致'],
                    ['password_confirm', 'require', '重复密码不能为空'],

                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }
                //验证代理商名是否存在
                $name = $model->where('name',$post['name'])->select();
                if(!empty($name)) {
                    return $this->error('提交失败：该代理商名字已被注册');
                }
                //验证账号是否存在
                $phone = $model->where('phone',$post['phone'])->select();
                if(!empty($phone)) {
                    return $this->error('提交失败：该手机号已被注册');
                }

                if(!preg_match("/^1[34578]{1}\d{9}$/",$post['phone'])){
                    return $this->error('提交失败：该手机号不正确');
                }
                // 密码处理
                $post['password'] = password($post['password']);
                $post['add_time'] = time();
                $post['update_time'] = '';


                // 启动事务
                $id = Session::get('admin');
                $cate_id = Db::name('admin')->where('id',$id)->value('admin_cate_id');
                $phone = Db::name('admin')->where('id',$id)->value('name');
                $pid = Db::name('agent')->where('phone',$phone)->value('id');
                if(!$pid){
                    $pid=0;
                }

              

                // 启动事务
                Db::startTrans();
                $n =0;
                try{
                    $list = $model->allowField(true)->save($post);
//                    $phone = $post['phone'];
                    $id= $model->where('phone',$post['phone'])->value('id');
                    $data['grade'] =$post['grade'];
                    $data['charge_ratio']=$post['charge_ratio'];
                    $data['agent_id']=$id;
                    $data['pid'] = $pid;
                    $data['request'] = substr(strval(rand(1000000,1999999)),1,6);

                    $rb = Db::name('ratio')->insert($data);


                   
                    // 提交事务
                    if($list && $rb){
                        Db::commit();
                        $n = 1;
                    }
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                }

                if(!$n) {
                    return $this->error('添加失败');
                } else {
                    if($cate_id==1){
                         return $this->success('添加成功','admin/agents/index');
                     }else{
                         return $this->success('添加成功','admin/agent/index');
                     }
                   
                }
            }
            $id = Session::get('admin');
            $ra = Db::name('admin')->where('id',$id)->value('admin_cate_id');


            $this->assign('ra',$ra);
            return $this->fetch();
        }
    }


    /**
     * 修改密码
     * @return [type] [description]
     */
    public function editPassword()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if($id > 0) {
            if($id == Session::get('admin')) {
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['password', 'require|confirm', '密码不能为空|两次密码不一致'],
                    ['password_confirm', 'require', '重复密码不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }
                $admin = Db::name('admin')->where('id',$id)->find();
                if(password($post['password_old']) == $admin['password']) {
                    if(false == Db::name('admin')->where('id',$id)->update(['password'=>password($post['password'])])) {
                        return $this->error('修改失败');
                    } else {
                        addlog();//写入日志
                        return $this->success('修改成功','admin/main/index');
                    }
                } else {
                    return $this->error('原密码错误');
                }
            } else {
                return $this->error('不能修改别人的密码');
            }
        } else {
            $id = Session::get('admin');
            $this->assign('id',$id);
            return $this->fetch();
        }
    }


    /**
     * 删除
     * @return [type] [description]
     */
    public function delete()
    {
        if($this->request->isAjax()) {
            $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
            $list = Db::name('agent')->where('id',$id)->delete();
          
            if($list){
                $ratio = Db::name('ratio')->where('agent_id',$id)->delete();
                if($ratio){
                   return $this->success('删除成功','admin/agent/index');
                }else{
                  return $this->error('删除失败');  
                 }
                }else{
                  return $this->error('删除失败'); 
            }
              

        }
    }


      

    /**
     * 管理员权限分组列表
     * @return [type] [description]
     * 会员->管理员->权限组中的角色管理
     */
    public function adminCate()
    {
        $model = new \app\admin\model\AdminCate;

        $post = $this->request->param();
        if (isset($post['keywords']) and !empty($post['keywords'])) {
            $where['name'] = ['like', '%' . $post['keywords'] . '%'];
        }

        if(isset($post['create_time']) and !empty($post['create_time'])) {
            $min_time = strtotime($post['create_time']);
            $max_time = $min_time + 24 * 60 * 60;
            $where['create_time'] = [['>=',$min_time],['<=',$max_time]];
        }

        $cate = empty($where) ? $model->order('create_time desc')->paginate(20) : $model->where($where)->order('create_time desc')->paginate(20,false,['query'=>$this->request->param()]);

        $this->assign('cate',$cate);
        return $this->fetch();

    }


    /**
     * 管理员角色添加和修改操作
     * @return [type] [description]
     */
    public function adminCatePublish()
    {
        //获取角色id
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $model = new \app\admin\model\AdminCate();
        $menuModel = new AdminMenu();
        if($id > 0) {
            //是修改操作
            if($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['name', 'require', '角色名称不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }
                //验证用户名是否存在
                $name = $model->where(['name'=>$post['name'],'id'=>['neq',$post['id']]])->select();
                if(!empty($name)) {
                    return $this->error('提交失败：该角色名已存在');
                }
                //处理选中的权限菜单id，转为字符串
                if(!empty($post['admin_menu_id'])) {
                    $post['permissions'] = implode(',',$post['admin_menu_id']);
                } else {
                    $post['permissions'] = '0';
                }
                if(false == $model->allowField(true)->save($post,['id'=>$id])) {
                    return $this->error('修改失败');
                } else {
                    addlog($model->id);//写入日志
                    return $this->success('修改角色信息成功','admin/admin/adminCate');
                }
            } else {
                //非提交操作
                $info['cate'] = $model->where('id',$id)->find();
                if(!empty($info['cate']['permissions'])) {
                    //将菜单id字符串拆分成数组
                    $info['cate']['permissions'] = explode(',',$info['cate']['permissions']);
                }
                $menus = Db::name('admin_menu')->select();
                $info['menu'] = $this->menulist($menus);
                $this->assign('info',$info);
                return $this->fetch();
            }
        } else {
            //是新增操作
            if($this->request->isPost()) {
                //是提交操作
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['name', 'require', '角色名称不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }
                //验证用户名是否存在
                $name = $model->where('name',$post['name'])->find();
                if(!empty($name)) {
                    return $this->error('提交失败：该角色名已存在');
                }
                //处理选中的权限菜单id，转为字符串
                if(!empty($post['admin_menu_id'])) {
                    $post['permissions'] = implode(',',$post['admin_menu_id']);
                }
                if(false == $model->allowField(true)->save($post)) {
                    return $this->error('添加角色失败');
                } else {
                    addlog($model->id);//写入日志
                    return $this->success('添加角色成功','admin/admin/adminCate');
                }
            } else {
                //非提交操作
                $menus = Db::name('admin_menu')->select();
                $info['menu'] = $this->menulist($menus);
                //$info['menu'] = $this->menulist($info['menu']);
                $this->assign('info',$info);
                return $this->fetch();
            }
        }
    }


    public function preview()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $model = new \app\admin\model\AdminCate();
        $info['cate'] = $model->where('id',$id)->find();
        if(!empty($info['cate']['permissions'])) {
            //将菜单id字符串拆分成数组
            $info['cate']['permissions'] = explode(',',$info['cate']['permissions']);
        }
        $menus = Db::name('admin_menu')->select();
        $info['menu'] = $this->menulist($menus);
        $this->assign('info',$info);
        return $this->fetch();
    }


    protected function menulist($menu,$id=0,$level=0){

        static $menus = array();
        $size = count($menus)-1;
        foreach ($menu as $value) {
            if ($value['pid']==$id) {
                $value['level'] = $level+1;
                if($level == 0)
                {
                    $value['str'] = str_repeat('',$value['level']);
                    $menus[] = $value;
                }
                elseif($level == 2)
                {
                    $value['str'] = '&emsp;&emsp;&emsp;&emsp;'.'└ ';
                    $menus[$size]['list'][] = $value;
                }
                elseif($level == 3)
                {
                    $value['str'] = '&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;'.'└ ';
                    $menus[$size]['list'][] = $value;
                }
                else
                {
                    $value['str'] = '&emsp;&emsp;'.'└ ';
                    $menus[$size]['list'][] = $value;
                }

                $this->menulist($menu,$value['id'],$value['level']);
            }
        }
        return $menus;
    }


    /**
     * 管理员角色删除
     * @return [type] [description]
     */
    public function adminCateDelete()
    {
        if($this->request->isAjax()) {
            $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
            if($id > 0) {
                if($id == 1) {
                    return $this->error('超级管理员角色不能删除');
                }
                if(false == Db::name('admin_cate')->where('id',$id)->delete()) {
                    return $this->error('删除失败');
                } else {
                    addlog($id);//写入日志
                    return $this->success('删除成功','admin/admin/adminCate');
                }
            } else {
                return $this->error('id不正确');
            }
        }
    }

    public function log()
    {
        $model = new \app\admin\model\AdminLog();

        $post = $this->request->param();
        if (isset($post['admin_menu_id']) and $post['admin_menu_id'] > 0) {
            $where['admin_menu_id'] = $post['admin_menu_id'];
        }

        if (isset($post['admin_id']) and $post['admin_id'] > 0) {
            $where['admin_id'] = $post['admin_id'];
        }

        if(isset($post['create_time']) and !empty($post['create_time'])) {
            $min_time = strtotime($post['create_time']);
            $max_time = $min_time + 24 * 60 * 60;
            $where['create_time'] = [['>=',$min_time],['<=',$max_time]];
        }

        $log = empty($where) ? $model->order('create_time desc')->paginate(20) : $model->where($where)->order('create_time desc')->paginate(20,false,['query'=>$this->request->param()]);

        $this->assign('log',$log);
        //身份列表
        $admin_cate = Db::name('admin_cate')->select();
        $this->assign('admin_cate',$admin_cate);
        $info['menu'] = Db::name('admin_menu')->select();
        $info['admin'] = Db::name('admin')->select();
        $this->assign('info',$info);
        return $this->fetch();
    }
}
